<?php


namespace app\shop\controller\api;

use app\Request;
use app\shop\model\config\TypeFieldModel;
use app\shop\model\user\ChatUserModel;
use app\shop\model\user\UserModel;
use app\shop\model\user\SmsModel;
use app\shop\model\order\OrderModel;
use app\shop\model\user\AdminRoleModel;
use app\shop\service\order\OrderService;
use app\shop\model\user\DepartmentModel;
use app\shop\model\file\FileModel;
use app\shop\model\user\MessageModel;
use app\shop\service\user\FriendService;
use app\shop\validate\EditInvoiceValidate;
use app\shop\validate\OrderValidate;
use app\shop\service\until\FileService;
use app\shop\common\consts\Consts;
use app\shop\common\consts\ReturnMethods;
use app\shop\service\until\SmsService;
use app\shop\model\config\TypePayModel;
use app\shop\model\config\TypeDesignModel;
use app\shop\model\config\TypeBusinessModel;
use app\shop\model\config\TypeProgramModel;
use app\BaseController;
use think\facade\Db;
use think\facade\Log;
use think\Validate;

class OrderController extends BaseController
{
    /**
     * 订单列表
     * @return \think\response\Json
     */
    public function orderList()
    {
        try {
            // 全部传空   0待分配 1进行中  2已定稿
            $orderStatus = $this->request->param('order_status', '', 'trim');
            // 搜索关键词
            $keyword = $this->request->param('keyword', '', 'trim');
            // 投诉订单
            $isComplaint = $this->request->param('is_complaint', '', 'trim');
            $page = $this->request->param('page', 1, 'int');
            $limit = $this->request->param('limit', 10, 'int');
            $userInfo = $this->request->middleware('userInfo');
            $list = OrderService::getOrderList($userInfo, $orderStatus, $keyword, $isComplaint, $page, $limit);
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage() . $exception->getLine());
        }
    }

    /**
     * 投诉订单
     * @return \think\response\Json
     */
    public function complaint()
    {
        Db::startTrans();
        try {
            $userInfo = $this->request->middleware('userInfo');
            $userRole = $userInfo->role_id;
            if ($userRole != Consts::CUSTOMER_ID) {
                throw new \Exception('只有客户可以投诉');
            }
            $id = $this->request->param('id', 0, 'int');
            $content = $this->request->param('complaint_content', '', ['trim']);
            if (!is_array($content)) {
                throw new \Exception('参数错误');
            }
            OrderService::complaintOrder($id, $content);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     *处理订单投诉
     * @return \think\response\Json
     */
    public function handle()
    {
        Db::startTrans();
        try {
            $userInfo = $this->request->middleware('userInfo');
            $userRoleId = $userInfo->role_id;
            if ($userRoleId != Consts::SERVICE_LEADER_ID) {
                throw new \Exception('只有售后总监可以处理');
            }
            $id = $this->request->param('id', 0, 'int');
            $designId = $this->request->param('design_id', 0, 'int');
            $solution = $this->request->param('solution', '', ['trim', 'htmlspecialchars']);

            OrderService::handleComplaintOrder($id, $designId, $solution);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 订单评价
     * @return \think\response\Json
     */
    public function evaluate()
    {
        Db::startTrans();
        try {
            $orderId = $this->request->param('id', 0, 'int');
            $evaluateInfo = $this->request->param('evaluate_info', '', ['trim']);
            if (!is_array($evaluateInfo)) {
                throw new \Exception('参数错误');
            }
            $userInfo = $this->request->middleware('userInfo');
            // 获取登陆者身份  根据身份判断
            $userRoleId = $userInfo->role_id;
            if ($userRoleId != Consts::CUSTOMER_ID) {
                throw new \Exception('只有客户可以评价');
            }
            OrderService::evaluateOrder($orderId, $evaluateInfo);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 部门成员
     * @return \think\response\Json
     */
    public function designer()
    {
        try {
            $keyword = $this->request->param('keyword', '', 'trim'); // 搜索关键词
            $userInfo = $this->request->middleware('userInfo');
            $list = OrderService::getDesignUserList($userInfo, $keyword);
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 订单指派设计师
     * @return \think\response\Json
     */
    public function assignDesigner()
    {
        Db::startTrans();
        try {
            $userInfo = $this->request->middleware('userInfo');
            $orderId = $this->request->param('orderId', '', 'trim');
            $designId = $this->request->param('designId', '', 'trim');
            $orderName = $this->request->param('order_name', '', 'trim');
            OrderService::assignDesigner($userInfo, $orderId, $designId, $orderName);
            Db::commit();
            return $this->success([], '设计师指派成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    //订单指派销售
    public function assignSales()
    {
        try {
            $orderId = $this->request->param('orderId', '', 'trim');
            $userId = $this->request->param('userId', '', 'trim');
            // 调用指派设计师的方法
            OrderService::assignSalesman($orderId, $userId);
            // 如果方法执行成功，返回成功信息
            return $this->success([], '销售指派成功');
        } catch (\Exception $exception) {
            // 如果有异常，返回错误信息
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 创建订单
     * @return \think\response\Json
     */
    public function estOrder()
    {
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');

            if (!in_array($userInfo['role_id'], [Consts::SALE_LEADER_ID, Consts::SALE_ID])) {
                throw new \Exception('您不能创建订单');
            }

            $data = $this->request->param('', '', ['trim', 'htmlspecialchars']);
            // 销售创建订单归属自己  销售总监创建订单可以指定销售
            $data["sale_id"] = $userId;
            $data['create_uid'] = $userId;
            OrderService::createOrder($data);
            return $this->success();
        } catch (\Exception $exception) {
            Log::error($exception->getMessage() . $exception->getLine());
            return $this->error($exception->getMessage());
        }
    }


    //补充需求
    public function supplement()
    {
        try {
            $data = $this->request->only(['id', 'replenish_need', 'replenish_need_file']);
            Validate(OrderValidate::class)->scene('supplement')->check($data);

            $orderId = $data["id"];
            $order = OrderModel::find($orderId);
            // 检查订单是否已经有补充需求
            if (!empty($order->replenish_need)) {
                throw new \Exception('需求已经补充过，不能再次添加。');
            }
            // 更新订单的补充需求
            $order->replenish_need = $data['replenish_need'];
            $order->replenish_need_file = $data['replenish_need_file'];
            $order->save();

            return $this->success('需求补充成功');
        } catch (\Exception $exception) {
            // 如果有异常，返回错误信息
            return $this->error($exception->getMessage());
        }
    }

    //代收款返还路径选择
    public function returnPath()
    {
        try {
            $userId = $this->request->middleware('userId');
            //返还路径 1银行卡 2收款码 3原路返回
            $returnPath = $this->request->param('return_path', '', 'trim');
            // 订单id
            $orderId = $this->request->param('orderId', 0, 'int');
            // 查询订单
            $order = OrderModel::where('id', $orderId)->find();
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            if ($order->order_status != OrderModel::FINALIZE) {
                throw new \Exception('订单还未定稿');
            }
            if ($returnPath == ReturnMethods::PAYMENT_CODE_ID) {
                $bank = $this->request->param('return_bank_card', '', 'trim');
                $bankName = $this->request->param('return_bank_card_name', '', 'trim');
                if (empty($bank)) {
                    throw new \Exception('银行卡号不能为空');
                }
                if (empty($bankName)) {
                    throw new \Exception('银行卡姓名不能为空');
                }
                $order->return_path = ReturnMethods::PAYMENT_CODE_ID;
                $order->return_bank_card = $bank;
                $order->return_bank_card_name = $bankName;
                $order->save();
            } else if ($returnPath == ReturnMethods::BANK_CARD_ID) {
                $fileCode = $this->request->param('return_bay_code', '', 'trim');
                if (empty($fileCode)) {
                    throw new \Exception('请上传收款码');
                }

                $order->return_path = ReturnMethods::BANK_CARD_ID;
                $order->return_bay_code = $fileCode;
                $order->save();
            } else if ($returnPath == ReturnMethods::ORIGINAL_ROAD_ID) {
                $order->return_path = ReturnMethods::ORIGINAL_ROAD_ID;
                $order->save();
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 修改订单状态
     * @return \think\response\Json
     */
    public function orderState()
    {
        Db::startTrans();
        try {
            $orderId = $this->request->param('orderId', '', 'trim');
            $stateId = $this->request->param('state', '', 'trim');

            OrderService::setOrderStatus($orderId, $stateId);
            Db::commit();
            return $this->success('状态修改成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 暂停订单
     * @return \think\response\Json
     */
    public function stopOrder()
    {
        try {
            $id = $this->request->param('id');

            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['order_status'] != 1) {
                throw new \Exception('进行中订单才可以暂停');
            }
            $orderInfo->order_status = OrderModel::STOP_ORDER;
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 开始订单
     * @return \think\response\Json
     */
    public function startOrder()
    {
        try {
            $id = $this->request->param('id');

            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            $orderInfo->order_status = OrderModel::UNDERWAY;
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 聊天记录 订单那个位置的，设计师经理可以根据订单查询客户和设计师的聊天记录
     * @return \think\response\Json
     */
    public function getChatInfo()
    {
        try {
            $userId = $this->request->param('user_id'); // 客户
            $designId = $this->request->param('design_id'); // 设计师
            // 获取分页参数
            $page = $this->request->param('page', 'intval'); // 默认第一页
            $limit = $this->request->param('limit', 'intval'); // 默认每页10条
            // 如果$page为空，则赋值为1
            if (empty($page)) {
                $page = 1;
            }
            // 如果$limit为空，则赋值为10
            if (empty($limit)) {
                $limit = 10;
            }
            $sensitiveWordId = $this->request->param('sensitive_word_id'); // 敏感词ID
            // 构建查询
            $query = MessageModel::where(function ($query) use ($userId, $designId) {
                // 发送者是设计师，接收者是客户
                $query->where('from_user', $userId)->where('to_user', $designId)
                    ->whereOr(function ($query) use ($userId, $designId) {
                        // 发送者是客户，接收者是设计师
                        $query->where('from_user', $designId)->where('to_user', $userId);
                    });
            });
            // 如果有敏感词ID，则加入敏感词查询条件
            if (!empty($sensitiveWordId)) {
                $query->where('sensitive_word_id', $sensitiveWordId);
            }
            $list = $query->page($page)->limit($limit)->select()->toArray();
            // 获取总数
            $totalCount = $query->count();
            // 计算总页数
            $totalPages = ceil($totalCount / $limit);
            if (
                $page > $totalPages
            ) {
                return $this->error('已经是最后一页了', [], 200);
            }
            // 处理每条消息的用户信息和文件信息
            foreach ($list as &$v) {
                $v['from_user_name'] = UserModel::where('user_id', $v['from_user'])->value('realname', '');
                $v['to_user_name'] = UserModel::where('user_id', $v['to_user'])->value('realname', '');
                $v['from_user_avatar'] = UserModel::where('user_id', $v['from_user'])->value('avatar', '');
                $v['to_user_avatar'] = UserModel::where('user_id', $v['to_user'])->value('avatar', '');
                $v['file_src'] = FileModel::where('file_id', $v['file_id'])->value('src', '');
            }

            // 返回结果
            return $this->success([
                'list' => $list,
                'totalPages' => $totalPages,
                'page' => $page,
            ]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 下载退款凭证
     * @return \think\response\Json
     */
    public function refundVoucher()
    {
        try {
            $id = $this->request->param('id');

            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['order_status'] != OrderModel::REFUNDED_ORDER) {
                throw new \Exception('退款后订单才可以下载退款凭证');
            }
            return $this->success($orderInfo["varchar"]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 订单详情
     * @return \think\response\Json
     */
    public function orderDetails()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $orderId = $this->request->param('id');
            $order = OrderService::getOrderDetail($orderId, $userInfo);
            return $this->success($order);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage()); // 错误处理
        }
    }

    /**
     * 提交交稿时间
     * @return \think\response\Json
     */
    public function manuscriptTime()
    {
        try {
            $id = $this->request->param('id');
            $deliveryTime = $this->request->param('delivery_time');
            $orderInfo = OrderModel::find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            $orderInfo->delivery_time = $deliveryTime;
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取创建订单时的选项
     * @return \think\response\Json
     */
    public function getCreateOrderOptionArr()
    {
        try {
            $arr = OrderService::getCreateOrderOptionArr();
            return $this->success($arr);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 指派订单列表
     * @return \think\response\Json
     */
    public function assignOrders()
    {
        try {
            // 订单状态   为空全部订单    为0未指派订单     为1已指派   为2更换指派
            $orderStatus = $this->request->param('order_status', '', 'trim');
            $userInfo = $this->request->middleware('userInfo');
            $keyword = $this->request->param('keyword', '', 'trim');
            $page = $this->request->param('page', 1, 'int');
            $limit = $this->request->param('limit', 10, 'int');
            $list = OrderService::getAssignOrderList($userInfo, $orderStatus, $keyword, $page, $limit);
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage()); // 错误处理
        }
    }

    /**
     * 修改订单
     * @return \think\response\Json
     */
    public function updateOrder()
    {
        try {
            $data = $this->request->except(['create_time']);
            OrderService::updateOrder($data);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 订单扩展字段
     * @return \think\response\Json
     */
    public function getOrderFieldArr()
    {
        try {
            $list = TypeFieldModel::where('name', '<>', '')->select()->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 修改开票信息
     * @return \think\response\Json
     */
    public function editInvoiceInfo()
    {
        try {
            $data = $this->request->param('', '', 'trim');
            Validate(EditInvoiceValidate::class)->check($data);
            OrderService::editInvoiceInfo($data);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 修改订单子状态
     * @return \think\response\Json
     */
    public function setOrderSubStatus()
    {
        try {
            $id = $this->request->param('id', 0, 'int');
            $status = $this->request->param('status', 1, 'int');
            OrderService::setOrderSubStatus($id, $status);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 申请售后
     * @return \think\response\Json
     */
    public function applyOrderService()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id', 0, 'int');
            $userInfo = $this->request->middleware('userInfo');
            OrderService::applyOrderService($id, $userInfo);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 订单备忘录
     * @return \think\response\Json
     */
    public function setOrderMemo()
    {
        try {
            $id = $this->request->param('id', 0, 'int');
            $memo = $this->request->param('memo', '', 'trim');
            $orderInfo = OrderModel::find($id);
            $orderInfo->memo = $memo;
            $orderInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 删除订单
     * @return \think\response\Json
     */
    public function delOrder()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $id = $this->request->param('id', 0, 'int');
            OrderService::delOrder($id, $userInfo);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     *取用户可以设置的订单状态
     * @return \think\response\Json
     */
    public function getRoleOrderStatusArr()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $orderId = $this->request->param('order_id', 0, 'int');
            $arr = OrderService::getRoleOrderStatusArr($orderId, $userInfo);
            return $this->success($arr);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取关联订单
     * @return \think\response\Json
     */
    public function getRelatedOrder()
    {
        try {
            $orderId = $this->request->param('order_id', 0, 'int');

            $orderService = new OrderService();
            $list = $orderService->getRelatedOrder($orderId);
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 子订单指派设计师
     * @return \think\response\Json
     */
    public function assignSubOrderDesigner()
    {
        Db::startTrans();
        try {
            $userInfo = $this->request->middleware('userInfo');

            $orderId = $this->request->param('orderId', '', 'trim');
            $designId = $this->request->param('userId', '', 'trim');
            $orderName = $this->request->param('order_name', '', 'trim');

            OrderService::assignSubOrderDesigner($userInfo, $orderId, $designId, $orderName);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }
}
